﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sahit.iSoilHotel.Application.MainBoundedContext.Tavern.Interfaces;
using Sahit.iSoilHotel.Application.MainBoundedContext.DTO.AuthenticationAgg;
using Sahit.iSoilHotel.Domain.MainBoundedContext.Tavern.Aggregates.AuthenticationAgg;
using Sahit.iSoilHotel.Application.Seedwork;

namespace Sahit.iSoilHotel.Application.MainBoundedContext.Tavern.Services
{
    public class AccountService : IAccountService
    {
        #region Members

        private readonly IAccountRepository accountRepository;

        #endregion

        #region Constructor

        public AccountService(IAccountRepository accountRepository)
        {
            if (accountRepository == null)
                throw new ArgumentNullException("AccountRepository", "AccountRepository is null!");

            this.accountRepository = accountRepository;
        }
        #endregion

        #region IAccountService.Methods

        public bool ValidateAccount(string userName, string password)
        {
            bool isValid = false;
            var account = accountRepository.GetFiltered(a => a.Name == userName).FirstOrDefault<Account>();
            if (account == null)
            {
                isValid = false;
            }
            else if (account.Password == password)
            {
                isValid = true;
            }
            return isValid;
        }

        public AccountDTO GetAccountByUserName(string userName)
        {
            var account = accountRepository.GetFiltered(a => a.Name == userName).FirstOrDefault<Account>();
            return account.ProjectedAs<AccountDTO>();
        }
        #endregion


        public RegistrationResultDTO RegisterAccount(RegistrationRequestDTO registrationRequest)
        {
            RegistrationResultDTO registrationResult = new RegistrationResultDTO();
            Account registerAccount = registrationRequest.RegisterAccount;

            var account = accountRepository.GetFiltered(a => a.Name == registrationRequest.RegisterAccount.Name).FirstOrDefault<Account>();
            if (account != null)
            {
                registrationResult.AddError("The account has been registrated!");
            }
            else
            {
                registerAccount.GenerateNewIdentity();
                accountRepository.Add(registerAccount);
                accountRepository.UnitOfWork.Commit();
            }
            return registrationResult;
        }
    }
}
